<template>
  <el-container>
    <el-header style="height: 80px">
      <div class="header_logo">
        <img src="../assets/images/logos.png" alt="" />

        <div class="header_nav">
          <ul>
            <li
              v-for="(item, idx) in navData"
              :key="idx"
              class="iconfont"
              :class="[{ activeli: idx == routerNum }, item.icon]"
              @click="tagleItem(item, idx)"
            >
              {{ item.title }}
              <!-- <router-link :to="item.link" class="iconfont" :class="item.icon">
                {{ item.title }}
              </router-link>
              &nbsp;<i
                v-show="item.children"
                class="el-icon-arrow-down"
                :class="{ rotex: tagleitem }"
              ></i>
              <div class="itemRouter" v-show="tagleitem">
                <li v-for="(item, idx) in item.children" :key="idx">
                  <router-link
                    :to="item.link"
                    class="iconfont childern"
                    :class="item.icon"
                  >
                    {{ item.title }}
                  </router-link>
                </li>
              </div> -->
            </li>
          </ul>
        </div>
        <div class="header_myself">
          <span>{{ dates }} -- {{ str }}</span>
          <br />
          <span>用户：{{ username }} </span
          ><el-button size="mini" type="primary" @click="logout"
            >注销</el-button
          >
        </div>
      </div>
    </el-header>
    <el-main>
      <transition :leave-active-class="laveCss" :enter-active-class="enterCss">
        <keep-alive :include="keepLiveList">
          <router-view class="child-view" />
        </keep-alive>
      </transition>
    </el-main>
  </el-container>
</template>

<script>
import { queryTree } from "@/http";
import "animate.css";
export default {
  name: "Home",
  components: {},
  data() {
    return {
      keepLiveList: ["CondtionMonit", "OnlineMap", "Video", "QueryImg"],
      navData: [
        // {
        //   link: "/video",
        //   icon: "el-icon-setting",
        //   title: "数据概览",
        // },
        {
          id: 0,
          link: "/OnlineMap",
          icon: "el-icon-electronic-map",
          title: "电子地图",
        },
        {
          id: 1,
          link: "/Video",
          icon: "el-icon-shipinjiankong",
          title: "视频监控",
        },
        {
          id: 2,
          link: "/CondtionMonit",
          icon: "el-icon-zhuangtaijiankong",
          title: "状态监控",
        },
        {
          id: 3,
          link: "/QueryImg",
          icon: "el-icon-lishichaxun",
          title: "历史查询",
        },
        {
          id: 4,
          link: "/Organizations",
          icon: "el-icon-yewuguanli",
          title: "组织设备",
          // children: [
          //   {
          //     link: "/DeviceManagement",
          //     icon: "el-icon-yewuguanli",
          //     title: "设备管理",
          //   },
          //   {
          //     link: "/Organization",
          //     icon: "el-icon-yewuguanli",
          //     title: "组织管理",
          //   },
          //   {
          //     link: "/Organization2",
          //     icon: "el-icon-yewuguanli",
          //     title: "组织管理2",
          //   },
          // ],
        },
        {
          id: 5,
          link: "/UserManage",
          icon: "el-icon-yonghuguanli",
          title: "用户管理",
        },
        {
          id: 6,
          link: "/Log",
          icon: "el-icon-xitongrizhi",
          title: "日志管理",
        },
      ],
      str: "",
      dates: "",
      socket: null,
      reconnectData: null,
      lockReconnect: false, //避免重复连接，因为onerror之后会立即触发 onclose
      timeout: 60000, //60s一次心跳检测
      timeoutObj: null,
      serverTimeoutObj: null,
      timeval: null, //定时发送心跳
      routerNum: "",
      enterCss: "",
      laveCss: "",
    };
  },
  created() {
    this.getTreeData();
  },
  watch: {
    $route: {
      handler: function (to) {
        this.navData.forEach((item) => {
          item.link == to.path ? (this.routerNum = item.id) : "";
        });
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    var date = new Date();
    var a = ["日", "一", "二", "三", "四", "五", "六"];
    var week = new Date().getDay();
    this.str = "星期" + a[week];
    this.dates = date.toLocaleDateString();
    this.init();
  },
  computed: {
    // console.log(this.$store.state.username);
    username() {
      return localStorage.getItem("username");
    },
  },
  methods: {
    // 定时请求tree
    getTreeData() {
      queryTree().then((res) => {
        if (res.result_code == 200) {
          this.$store.commit("setTreeData", res.data);
          res.data.forEach((ele) => {
            ele.children.forEach((el2) => {
              let datals = [];
              if (el2.children) {
                el2.children.forEach((el3) => {
                  if (el3.nvr_IMEI) {
                    datals.push(el3);
                  }
                  if (el3.children) {
                    el3.children.forEach((el4) => {
                      datals.push(el4);
                      this.$store.commit("setNvrData", datals);
                    });
                  }
                });
              }
            });
          });

          setTimeout(() => {
            this.getTreeData();
          }, 1000 * 5 * 60);
        }
      });
    },

    logout() {
      localStorage.setItem("Authorization", "");
      this.$router.push("/Login");
    },
    // init websockte
    init: function (name = localStorage.getItem("username")) {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持webSocket!无法接收到实时消息!");
      } else {
        // 实例化socket
        this.socket = new WebSocket(
          "ws://192.168.15.238:6015/platform/nvr_tcp/api/websocket/" + name
        );
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        // 监听socket消息
        this.socket.onmessage = this.getMessage;
        this.socket.onclose = this.websocketclose;
      }
    },
    open: function () {
      console.log("socket连接成功");
      this.heatBeat2();
    },
    error: function () {
      console.log("连接错误");
      this.reconnect();
    },
    getMessage: function (msg) {
      // this.heatBeat(); //收到消息会刷新心跳检测，如果一直收到消息，就推迟心跳发送
      let data = JSON.parse(msg.data);
      switch (data.type) {
        case "heart":
          break;
        case "Success":
          this.$store.commit("setPicture", false);
          this.$message.success("操作完成!");
          break;
        case "Fail":
          this.$store.commit("setPicture", false);
          this.$message.warning("操作失败!");
          break;
        case "videoCutoff":
          this.$store.commit("setVideoEnd", true);
          break;
        default:
          break;
      }
    },
    websocketclose() {
      console.log("断开连接");
      this.reconnect();
    },
    send: function (data) {
      this.socket.send(JSON.stringify(data));
    },
    reconnect() {
      if (this.lockReconnect) {
        return; //这里很关键，因为连接失败之后之后会相继触发 连接关闭，不然会连接上两个 WebSocket
      }
      this.lockReconnect = true;
      this.reconnectData && clearTimeout(this.reconnectData);
      this.reconnectData = setTimeout(() => {
        this.init();
        this.lockReconnect = false;
      }, 15000);
    },
    heatBeat() {
      this.timeoutObj && clearTimeout(this.timeoutObj);
      this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
      this.timeoutObj = setTimeout(() => {
        this.send({ type: "heart" }); //根据后台要求发送
        this.serverTimeoutObj = setTimeout(() => {
          this.socket.onclose(); //如果  5秒之后我们没有收到 后台返回的心跳检测数据 断开socket，断开后会启动重连机制
        }, 5000);
      }, this.timeout);
    }, //心跳检测
    heatBeat2() {
      clearInterval(this.timeval);
      this.timeval = setInterval(() => {
        this.send({ type: "heart" });
      }, 1000 * 60);
    },
    tagleItem(item, key) {
      key > this.routerNum
        ? ((this.enterCss = "animate__animated animate__fadeInRightBig"),
          (this.laveCss = "animate__animated animate__fadeOutLeftBig"))
        : ((this.enterCss = "animate__animated animate__fadeInLeftBig"),
          (this.laveCss = "animate__animated animate__fadeOutRight"));

      this.$router.push(item.link);
    },
  },
};
</script>

<style lang="less" scoped>
body {
  .bgcor(#081832);
}
.el-header {
  .bgcor(#030829);
  color: white;
  box-shadow: -5px 0 15px 0px #030829;
}
.header_logo {
  text-align: right;
  img {
    .fl;
    width: 270px;
    padding-top: 16px;
  }
  .header_nav {
    .fl;
    margin-left: 40px;
    & > ul > li {
      .fl;
      cursor: pointer;
      .fsize(16px);
      line-height: 50px;
      padding: 18px 15px 8px;
      // &:hover > a {
      //   color: #25b5a7;
      // }

      // & > a {
      //   color: white;
      // }
      // .childern {
      //   line-height: 20px;
      // }
    }
    .activeli {
      .bor-btm(2px,#3adbcc);
      color: #3adbcc;
      .router-link-active {
        color: #3adbcc;
      }
      i {
        color: #3adbcc;
      }
    }
    .rotex {
      transform: rotate(-90deg);
    }
  }
  .header_myself {
    float: right;
    padding-top: 10px;
    line-height: 30px;
  }
}
.el-main {
  padding-bottom: 0;
}
.child-view {
  box-sizing: border-box;
  width: 98vw;
  position: absolute;
  top: 100px;
  left: 20px;
}
</style>
